<template>
  <div>
    <el-row
      type="flex"
      justify="space-between"
      align="middle"
      style="margin-bottom: 10px"
    >
      <el-col
        :lg="7"
        style="display: flex; align-items: center"
      >
        项目名称：
        <el-select
          style="flex: 1"
          v-model="projectId"
          placeholder="请选择"
        >
          <el-option
            v-for="item in projectOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-col>
      <el-col
        :lg="7"
        style="display: flex; align-items: center"
        >受检基地：
        <el-input
          style="flex: 1"
          v-model="projectShortName"
          placeholder="请输入受检基地"
        ></el-input>
      </el-col>
      <el-col
        :lg="7"
        style="display: flex; align-items: center"
        >分部名称：
        <el-cascader
          style="flex: 1"
          v-model="idArr"
          :options="davisOptions"
          @change="branchForMaterHandler"
          :props="props"
        ></el-cascader>
      </el-col>
    </el-row>
    <el-row
      style="margin-bottom: 10px"
      type="flex"
      justify="start"
    >
      <el-col :span="12">
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="addHandler"
        >
          新增</el-button
        >
        <el-button
          type="primary"
          icon="el-icon-download"
          @click="batchExportHandler"
        >
          批量导出</el-button
        >
      </el-col>
      <el-col
        :lg="12"
        style="text-align: right"
      >
        <el-button
          type="primary"
          @click="searchHandler"
          >查询</el-button
        ><el-button
          plain
          @click="resetHandler"
          >重置</el-button
        >
      </el-col>
    </el-row>
    <el-row>
      <el-table
        :data="renderData"
        @selection-change="handleSelectionChange"
        border
        style="width: 100%"
        :header-cell-style="{ background: '#606266', color: '#fff' }"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
        >
        </el-table-column>
        <el-table-column
          type="index"
          label="序号"
          width="80"
          align="center"
        />
        <el-table-column
          label="关联计划"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.planTypeNamess }}
          </template>
        </el-table-column>
        <el-table-column
          prop="baseCheck"
          label="受检基地"
          align="center"
        />
        <el-table-column
          prop="baseLeaderName"
          label="受检基地负责人"
          align="center"
          min-width="100"
        >
          <template slot-scope="scope">
            {{ scope.row.baseLeaderName }}
          </template>
        </el-table-column>
        <el-table-column
          prop="checkBranch"
          label="受检工程名称及部位"
          min-width="150"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="receiveDate"
          label="收件日期"
          align="center"
        />
        <el-table-column
          prop="sendDate"
          label="发出日期"
          align="center"
        />
        <el-table-column
          prop="checkPerson"
          label="检查人员"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.checkPersonName }}
          </template>
        </el-table-column>
        <el-table-column
          label="问题整改报告"
          min-width="200"
          align="center"
        >
          <template slot-scope="scope">
            <div
              v-if="scope.row.reportPath == null"
              style="color: rgb(199, 199, 199); font-size: 0.8rem"
            >
              暂无文件
            </div>
            <div
              v-else
              style="text-align: left"
            >
              <span
                @click="showFile(scope.row)"
                class="pHover"
                title="点击下载"
              >
                质量整改通知书--{{ scope.row.checkBranch }}--{{
                  scope.row.receiveDate
                }}
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="附件列表"
          prop="annexList"
          min-width="200"
        >
          <template slot-scope="scope">
            <div
              v-if="
                scope.row.annexList.length == 0 || scope.row.annexList == null
              "
              style="color: rgb(199, 199, 199); font-size: 0.8rem"
            >
              暂无附件
            </div>
            <div
              v-else
              style="text-align: left"
            >
              <div
                @click="showFile(item)"
                class="imgHover"
                v-for="(item, index) in scope.row.annexList"
                :key="index"
                title="点击下载"
              >
                <img
                  style="width: 80px; height: 80px"
                  :src="item.path"
                />
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="100"
          align="center"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="editHandler(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="text"
              style="color: red"
              @click="deleteProblemRectifyApi({ idList: [scope.row.id] })"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row style="position: absolute; right: 50px">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50]"
        :page-size="10"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-row>
  </div>
</template>

<script>
import {
  getProblemRectifyPage,
  deleteProblemRectify,
} from '../../../http/inTellingSchedule/problemRectify.js'
import { getrelaySchemaList } from '../../../http/inTellingSchedule/inspectBatch.js'
import {
  getProjectList,
  getBranchItemList,
  downloadFile,
} from '../../../http/commonApi.js'
import { getMaterialInfoByItem } from '../../../http/inTellingSchedule/branchItem.js'
import { blobToBase64 } from '../../../utils/autoClick.js'
export default {
  data() {
    return {
      projectShortName: '',
      relaySchemaOptions: [],
      idArr: [],
      projectOptions: [],
      davisOptions: [],
      materOptions: [],
      projectId: null,
      checkBranch: '',
      total: 0,
      pageSize: 10,
      currentPage: 1,
      isSearch: false,
      renderData: [],
      props: {
        value: 'id',
        label: 'name',
        children: 'itemList',
        leaf: 'leaf',
      },
      // 文件
      addArr: [],
      src: null,
      multipleSelection: [],
    }
  },

  mounted() {
    this.getBranchItemListApi()
    this.getProjectListApi()
    this.getrelaySchemaListApi(15)
    this.getProblemRectifyPageApi()
  },

  methods: {
    branchForMaterHandler(v) {
      console.log('v::: ', v)
      getMaterialInfoByItem({ id: v[1] }).then((res) => {
        if (res.code == 200) {
          console.log('res::: ', res)
          this.materOptions = res.data
        }
      })
    },
    // 勾选
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 每页几条
    handleSizeChange(v) {
      this.pageSize = v
      this.currentPage = 1
      if (this.isSearch === true) {
        this.getProblemRectifyPageApi(
          1,
          v,
          this.projectId,
          this.baseCheck,
          this.checkBranch
        )
      } else {
        this.getProblemRectifyPageApi(1, v)
      }
    },
    // 分页
    handleCurrentChange(v) {
      this.currentPage = v
      if (this.isSearch === true) {
        this.getProblemRectifyPageApi(
          v,
          this.pageSize,
          this.projectId,
          this.baseCheck,
          this.checkBranch
        )
      } else {
        this.getProblemRectifyPageApi(v, this.pageSize)
      }
    },
    // 新增
    addHandler() {
      this.$router.push('/addProblemRectify')
    },
    // 查询
    searchHandler() {
      this.currentPage = 1
      this.getProblemRectifyPageApi(
        1,
        this.pageSize,
        this.projectId,
        this.baseCheck,
        this.checkBranch
      )
    },
    // 重置
    resetHandler() {
      this.isSearch = false
      this.projectId = null
      this.baseCheck = ''
      this.checkBranch = ''
      this.getProblemRectifyPageApi(1, 10)
    },
    // 编辑
    editHandler(row) {
      this.$router.push({ name: 'addProblemRectify', params: row })
    },
    //获取文件对象
    getFile(event, id) {
      this.addArr = []
      this.renderData.forEach((el) => {
        if (el.id === id) {
          var file = event.target.files
          for (var i = 0; i < file.length; i++) {
            //    上传类型判断
            var imgName = file[i].name
            var idx = imgName.lastIndexOf('.')
            if (idx != -1) {
              var ext = imgName.substr(idx + 1).toUpperCase()
              ext = ext.toLowerCase()
              if (
                ext != 'pdf' &&
                ext != 'doc' &&
                ext != 'docx' &&
                ext != 'xls'
              ) {
                this.$message.error(
                  '文件格式不正确，请重新上传格式为doc、docx、xls、pdf的文件'
                )
              } else {
                const filePath = URL.createObjectURL(file[i])
                file[i].filePath = filePath
                this.addArr.push(file[i])
              }
            } else {
              console.log('2::: ', 2)
            }
          }
          if (el.otherExam === null) {
            el.otherExam = this.addArr
          } else {
            el.otherExam.push(this.addArr[0])
          }
        }
      })
    },
    // 文件预览
    showFile(v) {
      console.log('v::: ', v)
      // if(v.)
      downloadFile({ path: v.reportPath }).then((res) => {
        let url = URL.createObjectURL(res)
        // 创建a 标签
        const a = document.createElement('a')
        const e = document.createEvent('MouseEvents') // 创建鼠标事件对象
        e.initEvent('click', false, false) // 初始化事件对象
        a.href = url // 设置下载地址
        a.download = `问题整改报告--${v.checkBranch}--${v.receiveDate}.docx` // 设置下载文件名
        a.dispatchEvent(e)
      })
    },
    // 批量导出
    batchExportHandler() {
      console.log('this.multipleSelection::: ', this.multipleSelection)
      if (this.multipleSelection.length == 0) {
        this.$message.error('请勾选导出项')
      } else {
        this.multipleSelection.forEach((el) => {
          if (el.otherExam != null) {
            // 创建a 标签
            const a = document.createElement('a')
            const e = document.createEvent('MouseEvents') // 创建鼠标事件对象
            e.initEvent('click', false, false) // 初始化事件对象
            el.otherExam.forEach((item) => {
              if (item.name === '测试文件.doc') {
                let file = null
                fetch(item.filePath)
                  .then((res) => res.blob)
                  .then((blob) => {
                    console.log('blob::: ', blob)
                    const fileName = item.name
                    file = new File(['测试文件'], fileName)
                    let src = URL.createObjectURL(file)
                    // 创建a 标签
                    const a = document.createElement('a')
                    const e = document.createEvent('MouseEvents') // 创建鼠标事件对象
                    e.initEvent('click', false, false) // 初始化事件对象
                    a.href = src // 设置下载地址
                    a.download = item.name // 设置下载文件名
                    a.dispatchEvent(e)
                  })
              } else {
                a.href = item.filePath // 设置下载地址
                a.download = item.name // 设置下载文件名
                a.dispatchEvent(e)
              }
            })
          } else {
            this.$message.warning('该项没有可导出的文件')
          }
        })
      }
    },
    /**
     * 接口
     */
    // 获取项目列表
    getProjectListApi() {
      getProjectList().then((res) => {
        if (res.code == 200) {
          this.projectOptions = res.data
        }
      })
    },
    // 分部分项列表
    getBranchItemListApi() {
      getBranchItemList().then((res) => {
        if (res.code == 200) {
          this.davisOptions = res.data
        }
      })
    },
    // 获取关联计划列表
    getrelaySchemaListApi(id) {
      getrelaySchemaList({ id }).then((res) => {
        if (res.code == 200) {
          this.relaySchemaOptions = res.data
          this.relaySchemaOptions.forEach((el) => {
            el.id = el.planType
            el.name = el.planTypeName
            if (el.projectPlans.length != 0 && el.projectPlans != null) {
              el.projectPlans.forEach((item) => {
                item.name = item.planCycleStart + '~' + item.planCycleEnd
              })
            }
          })
        }
      })
    },
    //  分页查询
    async getProblemRectifyPageApi(
      pageNum = 1,
      pageSize = 10,
      projectId = null,
      baseCheck = '',
      checkBranch = ''
    ) {
      let params = { pageNum, pageSize, projectId, baseCheck, checkBranch }
      try {
        const res = await getProblemRectifyPage(params)
        if (res.code === 200) {
          await Promise.all(
            res.data.records.map(async (item) => {
              if (item.annexList != null) {
                await Promise.all(
                  item.annexList.map(async (annex) => {
                    const resImg = await downloadFile({ path: annex.path })
                    const resBase64 = await blobToBase64(resImg)
                    annex.path = resBase64
                  })
                )
              }
              let s = this.relaySchemaOptions.filter((a) => {
                return a.id === item.planType
              })[0].planTypeName
              let e =
                this.relaySchemaOptions
                  .filter((a) => {
                    return a.id === item.planType
                  })[0]
                  .projectPlans.filter((t) => {
                    return t.id === item.planId
                  })[0] == undefined
                  ? '--'
                  : this.relaySchemaOptions
                      .filter((a) => {
                        return a.id === item.planType
                      })[0]
                      .projectPlans.filter((t) => {
                        return t.id === item.planId
                      })[0].name
              item.planTypeNamess = '[' + s + ']' + '/' + e
            })
          )
          this.renderData = res.data.records
          this.total = res.data.total
        }
      } catch (error) {
        console.error(error)
      }
    },

    // 删除
    deleteProblemRectifyApi(params) {
      this.$confirm('此操作将永久删除该条信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          deleteProblemRectify(params).then((res) => {
            if (res.code == 200) {
              this.$message.success('删除成功')
            } else {
              this.$message.error(res.message)
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
  },
}
</script>

<style lang="less" scoped>
.fileBox {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: center;
  align-items: center;
  img {
    width: 40px;
    height: 40px;
    line-height: 40px;
    cursor: pointer;
  }
  img:hover {
    background-color: rgb(228, 228, 228);
    border-radius: 5px;
  }
  .uploadBtn {
    display: none;
  }
}
.fileBox:hover .uploadBtn {
  display: block;
}
.pHover,
.imgHover {
  display: inline-block;
  cursor: pointer;
  color: #4ea1db;
  font-size: 0.8rem;
  box-sizing: border-box;
}
.pHover:hover {
  color: #ca0c16;
  box-sizing: border-box;
  border-bottom: 1px solid #ca0c16;
}
</style>
